import os
import subprocess
import datetime

def run_command(command):
    try:
        # 直接在当前工作目录下执行命令
        result = subprocess.run(
            command,
            shell=True,
            check=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            encoding='utf-8',
            errors='replace'
        )
        print(f"执行成功: {command}")
        if result.stdout:
            print(result.stdout)
        return True
    except subprocess.CalledProcessError as e:
        print(f"执行失败: {command}")
        print(f"错误信息: {e.stderr}")
        return False

def git_backup(repo_path):
    print(f"\n--------------------------------")
    print(f"正在处理仓库: {repo_path}")
    
    if not os.path.exists(repo_path):
        print(f"错误: 路径不存在 {repo_path}")
        return

    # 关键修改：先切换到目标文件夹路径
    try:
        os.chdir(repo_path)
        print(f"已切换当前工作目录至: {os.getcwd()}")
    except Exception as e:
        print(f"错误: 无法进入目录 {repo_path}")
        print(f"原因: {e}")
        return

    target_branch = "master"

    # 切换到 master 分支
    try:
        # 先检查当前分支
        check_branch = subprocess.run(
            "git rev-parse --abbrev-ref HEAD",
            shell=True,
            stdout=subprocess.PIPE,
            encoding='utf-8',
            errors='replace'
        )
        current_branch = check_branch.stdout.strip()
        
        if current_branch != target_branch:
            print(f"当前分支为 {current_branch}，正在切换到 {target_branch}...")
            subprocess.run(
                f"git checkout {target_branch}",
                shell=True,
                check=True,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                encoding='utf-8',
                errors='replace'
            )
            print(f"已切换到 {target_branch}")
        else:
            print(f"当前已在 {target_branch} 分支")
            
    except subprocess.CalledProcessError as e:
        print(f"错误: 无法切换到 {target_branch} 分支")
        print(f"原因: {e.stderr}")
        # 如果切换失败，尝试创建并切换
        if "did not match" in str(e.stderr):
             print(f"本地不存在 {target_branch} 分支，尝试创建...")
             try:
                 subprocess.run(f"git checkout -b {target_branch}", shell=True, check=True)
             except subprocess.CalledProcessError:
                 print("创建分支失败，停止备份")
                 return
        else:
            return

    # 获取当前时间
    timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    commit_message = f"自动备份 {timestamp}"

    # 执行 git 命令
    # 顺序：添加 -> 提交 -> 拉取(合并) -> 推送
    commands = [
        "git add .",
        f'git commit -m "{commit_message}"',
        f"git pull origin {target_branch}",
        f"git push origin {target_branch}"
    ]

    for cmd in commands:
        # commit 命令如果没什么可提交的会返回非0，需要特殊处理
        if cmd.startswith("git commit"):
            try:
                result = subprocess.run(
                    cmd,
                    shell=True,
                    check=True,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    encoding='utf-8',
                    errors='replace'
                )
                print(f"执行成功: {cmd}")
                print(result.stdout)
            except subprocess.CalledProcessError as e:
                if "nothing to commit" in e.stdout or "nothing to commit" in e.stderr:
                    print("提示: 没有需要提交的更改")
                else:
                    print(f"执行失败: {cmd}")
                    print(f"错误信息: {e.stderr}")
        else:
            run_command(cmd)

if __name__ == "__main__":
    # 定义仓库路径
    repos = [
        r"f:\和臻OA\frontend",
        r"f:\和臻OA\backend"
    ]

    print("开始自动备份...")
    for repo in repos:
        git_backup(repo)
    print("\n所有备份任务完成！")
    input("按回车键退出...")
